#!/bin/bash
# 更新部署脚本

APP_DIR="/opt/erp-mock"
BACKUP_DIR="/opt/erp-mock-backup-$(date +%Y%m%d_%H%M%S)"

echo "========================================"
echo "ERP Mock Server 更新脚本"
echo "========================================"

# 检查是否为root用户
if [ "$EUID" -ne 0 ]; then
    echo "请使用sudo运行此脚本"
    exit 1
fi

# 1. 备份当前版本
echo ""
echo "[1/6] 备份当前版本..."
if [ -d "$APP_DIR" ]; then
    cp -r $APP_DIR $BACKUP_DIR
    echo "✓ 备份完成: $BACKUP_DIR"
else
    echo "✗ 应用目录不存在"
    exit 1
fi

# 2. 停止服务
echo ""
echo "[2/6] 停止服务..."
supervisorctl stop erp-mock
echo "✓ 服务已停止"

# 3. 更新代码
echo ""
echo "[3/6] 更新代码..."
cd $APP_DIR

# 如果使用Git
if [ -d ".git" ]; then
    echo "从Git拉取最新代码..."
    git fetch origin
    git pull origin master
    echo "✓ Git更新完成"
else
    echo "请手动上传新版本代码到 $APP_DIR"
    echo "按回车继续，或Ctrl+C取消..."
    read
fi

# 4. 更新依赖
echo ""
echo "[4/6] 更新Python依赖..."
source venv/bin/activate
pip install --upgrade pip -q
pip install -r requirements.txt -q
echo "✓ 依赖更新完成"

# 5. 启动服务
echo ""
echo "[5/6] 启动服务..."
supervisorctl start erp-mock
sleep 3
echo "✓ 服务已启动"

# 6. 验证更新
echo ""
echo "[6/6] 验证服务..."
if supervisorctl status erp-mock | grep -q RUNNING; then
    echo "✓ 服务运行正常"

    # 健康检查
    if curl -s http://127.0.0.1:3003/health > /dev/null; then
        echo "✓ 健康检查通过"
    else
        echo "✗ 健康检查失败"
        echo "正在回滚..."
        supervisorctl stop erp-mock
        rm -rf $APP_DIR
        mv $BACKUP_DIR $APP_DIR
        supervisorctl start erp-mock
        echo "✗ 更新失败，已回滚到之前版本"
        exit 1
    fi
else
    echo "✗ 服务启动失败"
    echo "正在回滚..."
    rm -rf $APP_DIR
    mv $BACKUP_DIR $APP_DIR
    supervisorctl start erp-mock
    echo "✗ 更新失败，已回滚到之前版本"
    exit 1
fi

echo ""
echo "========================================"
echo "✓ 更新完成！"
echo "========================================"
echo ""
echo "备份位置: $BACKUP_DIR"
echo "如需回滚，执行："
echo "  sudo supervisorctl stop erp-mock"
echo "  sudo rm -rf $APP_DIR"
echo "  sudo mv $BACKUP_DIR $APP_DIR"
echo "  sudo supervisorctl start erp-mock"
echo ""
